<?php  

/**
 * login.php
 *
 * Login management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestLogin extends RestController {

	const FACEBOOK_USER_INFORMATION_URL = 'https://graph.facebook.com/me?fields=email,name';
	const GOOGLE_USER_INFORMATION_URL = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json';

	/*
	* Login user
	*/
	public function login() {

		$this->checkPlugin();
		
		$json = array('success' => true);
		
		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
			
			$requestjson = file_get_contents('php://input');
		
			$requestjson = json_decode($requestjson, true);

			$post		 = $requestjson;

			$this->language->load('checkout/checkout');
				
			if ($this->customer->isLogged()) {
				// $json['error']['warning']	= "User already is logged";			
				$json['success']	= true;			
			}	
			
			if ($json['success']) {
				if (!$this->customer->login($post['email'], $post['password'])) {
					$json['error']['warning'] = $this->language->get('error_login');
					$json['success']	= false;
				}
			
				$this->load->model('account/customer');
			
				$customer_info = $this->model_account_customer->getCustomerByEmail($post['email']);
				
				if ($customer_info && !$customer_info['approved']) {
					$json['error']['warning'] = $this->language->get('error_approved');
					$json['success']	= false;
				}
				if ($customer_info['is_receive']==0) {
					$customer_info['is_receive'] = 0;
				}elseif($customer_info['is_receive']==1){
					$customer_info['is_receive'] = 1;

				}
				$customer_info['customer_id'] = (int)$customer_info['customer_id'];

				$myuser_id= $this->model_account_customer->getMyUserId($post['email']);
				if (empty($myuser_id)) {
					$customer_info['myuser_id'] = 0;
				}else{
					$customer_info['myuser_id'] = $myuser_id;

				}

			}
			
			if ($json['success']) {
				unset($this->session->data['guest']);
					
				// Default Addresses
				$this->load->model('account/address');
					
				if ($this->config->get('config_tax_customer') == 'payment') {
					$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
				}	

				if ($this->config->get('config_tax_customer') == 'shipping') {
					$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
				}

				// Add to activity log
				$this->load->model('account/activity');

				$activity_data = array(
					'customer_id' => $this->customer->getId(),
					'name'        => $this->customer->getFullName()
				);

				$this->model_account_activity->addActivity('login', $activity_data);				

				unset($customer_info['password']);
                unset($customer_info['token']);
                unset($customer_info['salt']);

				$customer_info["session"] = session_id();
				
				// Custom Fields
				$this->load->model('account/custom_field');

				$customer_info['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

                if(strpos(VERSION, '2.1.') === false){
                    $customer_info['account_custom_field'] = unserialize($customer_info['custom_field']);
                } else {
                    $customer_info['account_custom_field'] = json_decode($customer_info['custom_field'], true);
                }

				unset($customer_info['custom_field']);

			//如果没有头像或者头像不是默认头像
			if(isset($this->session->data['weixin_avatar'])) {
				if (empty($customer_info['avatar']) || !(strpos($customer_info['avatar'], 'default-avarta.png') === false)) {
					$code = $this->session->data['weixin_avatar'];
					$this->model_account_customer->saveAvatar($this->customer->getId(), $code);	      	
				}
			}

			//判断扫码获取coupon的session是否存在，如果存在的话
			if(isset($this->session->data['scan_coupon_code'])) {
				$scan_coupon_code = $this->session->data['scan_coupon_code'];
				//判断coupon是否合法(是否已经被绑定过，是否是有效的coupon)，如果合法
				$this->load->model('checkout/coupon');
				$error = $this->model_checkout_coupon->validateCoupon($scan_coupon_code);
				//判断coupon是否合法(是否已经被绑定过，是否是有效的coupon)，如果合法
				//将coupon放入用户名下
				if(empty($error)) {
					$this->model_checkout_coupon->assignCouponToCustomer($scan_coupon_code);
					unset($this->session->data['scan_coupon_code']);
				}
				unset($this->session->data['scan_coupon_code']);
			}


				$json['data'] = $customer_info;
			}
						
		}else {
				$json["error"]['warning']		= "Only POST request method allowed";
				$json["success"]	= false;
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}
	
	}

	/*
	Only for testing
	Depracted
	http:/opencart3.my/api/rest/checkuser/key/123
	*/	
	public function checkuser() {

		$json = array('success' => true);	

		if (!$this->customer->isLogged()) {
				$json['error']		= "User is not logged";			
				$json['success']	= false;			
		}else {
			$json['data'] 		= $this->customer->getEmail();			
		}
		
		if ($this->debugIt) {
				echo '<pre>';
				print_r($json);
		} else {
				$this->response->setOutput(json_encode($json));
		}
    }

	/*
	Set IsCheck
	*/	
	public function setIsCheck() {

		$json = array('success' => true);	

		$input = file_get_contents('php://input');
		$post = json_decode($input, true);

		$this->load->model('account/customer');
		$result = $this->model_account_customer->setIsCheck($post['customer_id']);
		
		if(!$result){
			$json = array('success' => false,'error'=>'更改失败');
		}

		if ($this->debugIt) {
				echo '<pre>';
				print_r($json);
		} else {
				$this->response->setOutput(json_encode($json));
		}
    }

	/*
	* Login user
	*/
	public function sociallogin() {

		$this->checkPlugin();

		$json = array('success' => true);
		$customer_info = array();
		$firstname = "";
		$lastname = "";
		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

			$input = file_get_contents('php://input');

			$post = json_decode($input, true);

			$this->language->load('checkout/checkout');

			if ($this->customer->isLogged()) {
				$json['error']		= "User already is logged";
				$json['success']	= false;
			}

			if ($json['success']) {
				$this->load->model('account/customer');

				$customer_info = $this->model_account_customer->getCustomerByEmail($post['email']);

				if(!isset($post['provider']) || ($post['provider'] != 'facebook' && $post['provider'] != 'google')) {
					$json['error']		= "Invalid social provider";
					$json['success']	= false;
				}

				if(isset($post['provider']) && ($post['provider'] == 'facebook' || $post['provider'] == 'google')) {
					$social = $this->requestUserDataFromProvider($post['provider'], $post['access_token']);

					if (empty($social) || $social['email'] != $post['email']) {
						$json['error'] = "Social email and posted email mismatch";
						$json['success'] = false;
					} else {
						if(isset($social['name'])){
							$exploded = explode(' ', $social['name']);
							$firstname = array_shift($exploded);
							$lastname= implode(' ', $exploded);
						}
					}
				}

				if($json['success']) {
					//if email does not exist, register as a new customer
					if (!$customer_info) {
						$data['email'] = $post['email'];
						$data['firstname'] = $firstname;
						$data['lastname'] = $lastname;
						$data['telephone'] = "";
						$data['address_1'] = "";
						$data['city'] = "";
						$data['postcode'] = "";
						$data['country'] = "";
						$data['zone_id'] = "";
						$data['approved'] = 1;
						$data['password'] = md5(microtime());

						$this->model_account_customer->addCustomer($data);
						$customer_info = $this->model_account_customer->getCustomerByEmail($post['email']);
					}

					if ($customer_info) {
						if (!$this->customer->login($post['email'], "", true)) {
							$json['error']['warning'] = $this->language->get('error_login');
							$json['success'] = false;
						}
					}

					if ($customer_info && !$customer_info['approved']) {
						$json['error']['warning'] = $this->language->get('error_approved');
						$json['success'] = false;
					}
				}
			}

			if ($json['success'] && !empty($customer_info)) {
				unset($this->session->data['guest']);

				// Default Addresses
				$this->load->model('account/address');

				if ($this->config->get('config_tax_customer') == 'payment') {
					$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
				}

				if ($this->config->get('config_tax_customer') == 'shipping') {
					$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
				}

				// Add to activity log
				$this->load->model('account/activity');

				$activity_data = array(
					'customer_id' => $this->customer->getId(),
					'name'        => $this->customer->getFirstName() . ' ' . $this->customer->getLastName()
				);

				$this->model_account_activity->addActivity('login', $activity_data);

				unset($customer_info['password']);
				unset($customer_info['token']);
				unset($customer_info['salt']);

				$customer_info["session"] = session_id();

				// Custom Fields
				$this->load->model('account/custom_field');

				$customer_info['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

				if(strpos(VERSION, '2.1.') === false){
					$customer_info['account_custom_field'] = unserialize($customer_info['custom_field']);
				} else {
					$customer_info['account_custom_field'] = json_decode($customer_info['custom_field'], true);
				}

				unset($customer_info['custom_field']);

				$json['data'] = $customer_info;
			}

		}else {
			$json["error"]		= "Only POST request method allowed";
			$json["success"]	= false;
		}

		$this->sendResponse($json);
	}

	private function requestUserDataFromProvider($provider, $access_token) {
		$ch = curl_init();
		if($provider == 'facebook'){
			curl_setopt($ch, CURLOPT_URL, static::FACEBOOK_USER_INFORMATION_URL);
		} elseif ($provider == 'google') {
			curl_setopt($ch, CURLOPT_URL, static::GOOGLE_USER_INFORMATION_URL);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
		$headers = array("Authorization: Bearer " . $access_token);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		// execute the CURL request.
		$data = curl_exec($ch);
		if(!curl_errno($ch)){
			curl_close($ch);
			return json_decode($data, true);
		} else {
			curl_close($ch);
			return NULL;
		}
	}
}